﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Brettle.Web.NeatUpload;
using System.IO;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Data;

public partial class up : System.Web.UI.Page
{
    public string UpPath = "/picture/file/" + String.Format("{0}/{1}/{2}/", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

 

    //初始化系统参数
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["sJigou"] == null || Session["sJigou"].ToString() == string.Empty)
        {
            return;
        }
        mapJigouId();
        if (IsPostBack)
        {
            DataBrid();
        }
    }



    /// <summary>
    /// 读取列表
    /// </summary>
    private void DataBrid()
    {
        string sqlText = " select * from TuPIanKu order by img_order desc ";
        imglist.DataSource = DbHelper.ExecuteTable(CommandType.Text,sqlText,null);
        imglist.DataBind();
    }

    /// <summary>
    /// 上传成功的文件保存进入数组，把数组放入session中在其它页面更新数据库
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button2_Click(object sender, EventArgs e)
    {
                foreach (UploadedFile item in multi.Files)
                {
                    //if (item.ContentLength > 100)
                    //{
                    //    uploadResult.Text = "上传图片不能超过100Kb";
                    //    return;
                    //}
                }
                string picLuJing = string.Empty;
                string picFileName = string.Empty;
                string id = string.Empty;
                foreach (UploadedFile item in multi.Files)
                {
                    string FileName = item.FileName;
                    string ChongMingMing = System.Guid.NewGuid().ToString() + Path.GetExtension(item.FileName);
                    string LuJing = Path.Combine("../systemConfig/customImages/", Session["JigouId"].ToString());
                    string target=Path.Combine(MapPath(LuJing), ChongMingMing);
                    FileInfo file=new FileInfo(target);
                    if (!Directory.Exists(file.DirectoryName))
                    {
                        Directory.CreateDirectory(file.DirectoryName);
                    }
                    item.MoveTo(target, MoveToOptions.Overwrite);
                    //生成缩略图
                    MakeSmallImg(Path.Combine(MapPath(LuJing), ChongMingMing), Path.Combine(MapPath(LuJing), "thumb_" + ChongMingMing), 200, 200);
                    //获取图片宽和高
                    System.Drawing.Image myImage = System.Drawing.Image.FromFile(Path.Combine(MapPath(LuJing), ChongMingMing));
                    string width = myImage.Width.ToString();
                    string height = myImage.Height.ToString();
                    string sql = string.Format("insert into TuPIanku (JiGouBiaoZhiFu,LuJing,ChongMingMing,TuPianMingCheng,LeiXing,width,height) values ({0},'{1}','{2}','{3}',1,{4},{5})", Session["JigouId"].ToString(), LuJing.Replace("../",""), ChongMingMing, FileName, width, height);
                    int num = DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
                    if (num == 0)
                    {
                        uploadResult.Text = "上传失败";
                    }
                }
     }
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="fromFileStream"></param>
    /// <param name="fileSaveUrl"></param>
    /// <param name="templateWidth"></param>
    /// <param name="templateHeight"></param>
    public static void MakeSmallImg(string fromFileStream, string fileSaveUrl, System.Double templateWidth, System.Double templateHeight)
    {
        if (Regex.IsMatch(Path.GetExtension(fromFileStream), "gif", RegexOptions.IgnoreCase))
        {
            File.Copy(fromFileStream, fileSaveUrl);
        }
        else
        {
            //从文件取得图片对象，并使用流中嵌入的颜色管理信息
            System.Drawing.Image myImage = System.Drawing.Image.FromFile(fromFileStream);

            //缩略图宽、高
            System.Double newWidth = myImage.Width, newHeight = myImage.Height;
            //宽大于模版的横图
            if (myImage.Width > myImage.Height || myImage.Width == myImage.Height)
            {
                if (myImage.Width > templateWidth)
                {
                    //宽按模版，高按比例缩放
                    newWidth = templateWidth;
                    newHeight = myImage.Height * (newWidth / myImage.Width);
                }
            }
            //高大于模版的竖图
            else
            {
                if (myImage.Height > templateHeight)
                {
                    //高按模版，宽按比例缩放
                    newHeight = templateHeight;
                    newWidth = myImage.Width * (newHeight / myImage.Height);
                }
            }

            //取得图片大小
            Size mySize = new Size((int)newWidth, (int)newHeight);
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(mySize.Width, mySize.Height);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空一下画布
            g.Clear(System.Drawing.Color.White);
            //在指定位置画图
            g.DrawImage(myImage, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            new System.Drawing.Rectangle(0, 0, myImage.Width, myImage.Height),
            System.Drawing.GraphicsUnit.Pixel);

            /////文字水印
            //System.Drawing.Graphics G = System.Drawing.Graphics.FromImage(bitmap);
            //System.Drawing.Font f = new Font("宋体", 10);
            //System.Drawing.Brush b = new SolidBrush(Color.Black);
            //G.DrawString("深圳泽维", f, b, 10, 10);
            //G.Dispose();

            /////图片水印
            //System.Drawing.Image copyImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/images/1.jpg"));
            //Graphics a = Graphics.FromImage(bitmap);
            //a.DrawImage(copyImage, new Rectangle(bitmap.Width - copyImage.Width, bitmap.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);

            //copyImage.Dispose();
            //a.Dispose();
            //copyImage.Dispose();

            //保存缩略图
            bitmap.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

            g.Dispose();
            myImage.Dispose();
            bitmap.Dispose();
        }
    }
    /// <summary>
    /// 生成图片列表
    /// </summary>
    /// <returns></returns>
    public string getImgs()
    {
        string sql = string.Format("select TuPianMingCheng,ChongMingMing,LuJing,[img_order] from TuPianKu where JiGoubiaoZhiFu={0} order by [img_order]", Session["JigouId"].ToString());
        SqlDataReader dr = DbHelper.ExecuteReader(CommandType.Text, sql, null);
        if (dr.HasRows)
        {
            string imgs = string.Empty;
            while (dr.Read())
            {
                imgs += string.Format("<div class='imgStyle' id='{0}'><img id='{0}a'  src='{1}'></img><a class='delPic' href='#' alt='{0}'>删除</a></div>", dr["ChongMingMing"].ToString(), Path.Combine("../" + dr["LuJing"].ToString(), "thumb_" + dr["ChongMingMing"].ToString()));
            }
            ///隐藏上传层,只显示排序层
            sort.Visible = true;
            return imgs;
        }
        else
        {
            upDiv.Visible = true;
            sort.Visible = false;
            return String.Empty;
        }
    }
    /// <summary>
    /// 处理排序结果
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void sort_Click(object sender, EventArgs e)
    {
        if (sortResult.Value != string.Empty)
        {
            string sortImages = sortResult.Value.Replace("imagesGallery[]=", "");
            string[] sortarr = sortImages.Split('&');
            for (int i = 0; i < sortarr.Length; i++)
            {
                string sql = string.Format("update TuPianKu set [img_order]={0} where ChongMingMing='{1}'", i, sortarr[i]);
                DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
            }
            uploadResult.Text = "排序成功,请关闭本窗口";
        }
    }
    /// <summary>
    /// 机构名称映射到唯一id
    /// </summary>
    void mapJigouId()
    {
        string sql = string.Format("select count(id) from JiGouPeiZhi where JiGouMingCheng='{0}'", Session["sJigou"].ToString());
        int num = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, null));
        if (num == 0)
        {
            sql = string.Format("insert into JiGouPeiZhi (JiGouMingCheng) values('{0}')", Session["sJigou"].ToString());
            num = DbHelper.ExecuteNonQuery(CommandType.Text, sql, null);
            if (num == 1)
            {
                sql = string.Format("select id from JiGouPeiZhi where JiGouMingCheng='{0}'", Session["sJigou"].ToString());
                Session["JigouId"] = DbHelper.ExecuteScalar(CommandType.Text, sql, null);
            }
            else
            {
                Response.Write(string.Format("<script language='javascript'>alert('{0}');</script>", "机构映射失败"));
            }
        }
        else
        {
            sql = string.Format("select id from JiGouPeiZhi where JiGouMingCheng='{0}'", Session["sJigou"].ToString());
            Session["JigouId"] = DbHelper.ExecuteScalar(CommandType.Text, sql, null);
        }
    }
    protected void btn_add_Click(object sender, EventArgs e)
    {
        string imgname = this.img_title.Text.Trim();
        string uploadname = string.Empty;
        if (this.filename.FileName != null)
        {
        filename.MoveTo(GetPath() + uploadname, Brettle.Web.NeatUpload.MoveToOptions.Overwrite);
        uploadname = UpPath + uploadname;
        }
        string sqlText = "insert into TuPIanKu(img_order,JiGouBiaoZhiFu,LuJing,font_img,visible)values('@img_order','@JiGouBiaoZhiFu','@LuJing','@font_img','@visible');";
        SqlParameter[] param = { new SqlParameter("@img_order",SqlDbType.Int),
                                 new SqlParameter("@JiGouBiaoZhiFu",SqlDbType.Int),
                                 new SqlParameter("@LuJing",SqlDbType.VarChar,100),
                                 new SqlParameter("@font_img",SqlDbType.NVarChar,50),
                                 new SqlParameter("@visible",SqlDbType.Int)
                                };
        param[0].Value = int.Parse(order_Index.Text.Trim());
        param[1].Value = int.Parse(Session["JigouId"].ToString());
        param[2].Value = uploadname;
        param[3].Value = img_title.Text.Trim();
        param[4].Value = 0;

        int id = DbHelper.ExecuteNonQuery(CommandType.Text, sqlText, param);
        if (id > 0)
        {
            Response.Write("<script>alert('添加成功');</script>");
        }
        else
        {
            Response.Write("<script>alert('添加失败');</script>");
        }

        DataBrid();
    }



    public string GetPath()
    {

        string path = Server.MapPath("~") + UpPath;
        if (!Directory.Exists(path))
        {
            try
            {
                Directory.CreateDirectory(path);
            }

            catch
            {
            }
        }
        return path;
    }


}
